package com.mars.quartz.scheduler.utils;

import java.util.Date;
import java.util.UUID;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SchedulerUtils {
	
	@Autowired
	private Scheduler scheduler;
	
	private static final String DEFAULT_CRON = "0/3 * * * * ?" ;
	
	/**
     * 获取触发器key
     */
    public TriggerKey getTriggerKey(String jobId) {
        return TriggerKey.triggerKey(jobId);
    }
    
    /**
     * 获取jobKey
     */
    public JobKey getJobKey(String jobId) {
        return JobKey.jobKey(jobId);
    }
    
    /**
     * 获取表达式触发器
     * @throws Exception 
     */
    public CronTrigger getCronTrigger(Scheduler scheduler, String jobId) throws Exception {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new Exception("获取定时任务CronTrigger出现异常", e);
        }
    }
	
	public void createScheduler(Class<? extends Job> clazz, String cron) throws SchedulerException {
		if(null == cron) {
			cron = DEFAULT_CRON ;
		}
		/*
		 * 任务：
		 * 1、给出实现了Job接口的类
		 * 2、withIdentity(jobName, groupName)
		 * 		jobName可以自己定义
		 * 		groupName 也可以用Scheduler提供的DEFAULT_GROUP
		 * 		这里要求同组里面的jobName不能相同
		 */
		JobDetail jobDetail = JobBuilder.newJob(clazz)
				.withIdentity("Job:"+UUID.randomUUID().toString().replaceAll("-", ""), Scheduler.DEFAULT_GROUP)
				.build() ;
		
		
		/*
		 * 触发器：
		 * 1、withIdentity(triggerName, groupName)
		 * 		triggerName可以自己定义
		 * 		groupName 也可以用Scheduler提供的DEFAULT_GROUP
		 * 		这里要求同组里面的triggerName不能相同
		 */
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity("Trigger:"+UUID.randomUUID().toString().replaceAll("-", ""), Scheduler.DEFAULT_GROUP)
				.withSchedule(CronScheduleBuilder.cronSchedule(cron))
				.build() ;
		
		/*
		 * 将任务和触发器交由调度器调度Job
		 */
		Date scheduleJob = this.scheduler.scheduleJob(jobDetail, trigger) ;
		System.out.println("开始调度任务：" + scheduleJob);
	}
	
	
	/**
	 * 重新设定任务执行时间
	 * @throws Exception 
	 */
	public void updateScheduleJob(String jobId, String cron) throws Exception {
		try {
			
			//取得久的TriggerKey
			TriggerKey triggerKey = getTriggerKey(jobId) ;
			
			//取得久的Trigger
			CronTrigger cronTrigger = getCronTrigger(this.scheduler, jobId) ;
			
			//修改触发时间
			cronTrigger = cronTrigger.getTriggerBuilder()
					.withIdentity(triggerKey)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron))
					.build() ;
			
			this.scheduler.rescheduleJob(getTriggerKey(jobId), cronTrigger) ;
			
			//判断该任务的状态是否暂停，如果状态为暂停的话，则将从新修改后的触发器设置为暂停
			//自己定义
			//if(scheduleJob.getStatus()) {
			//	pauseJob(jobId);
			//}
			
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 暂停任务
	 */
	public void pauseJob(String jobId) {
		try {
			System.out.println(getJobKey(jobId));
			this.scheduler.pauseJob(getJobKey(jobId));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 恢复任务
	 */
	public void resumeJob(String jobId) {
		try {
			System.out.println(getJobKey(jobId));
			this.scheduler.resumeJob(getJobKey(jobId));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	
	
}
